package com.aurora.gulimall.order.config;

import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Configuration
public class MyRabbitConfig {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 定制rabbittemplate
     */
    @PostConstruct //MyRabbitConfig对象创建完以后，执行这个方法
    public void initRabbitTemplate(){
        //设置确认回调
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            /**只要消息抵达服务器Broker ack=true
             * @param correlationData 当前消息的唯一关联数据（id，returnedMessage）
             * @param ack             true for ack, false for nack 消息是否成功收到
             * @param cause           失败原因
             */
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {

            }
        });
        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
            /**
             * 只要消息没有投递给指定的队列，就触发这个失败回调
             * @param returned the returned message and metadata.
             *                 	private final Message message  投递失败消息的详细信息
             *              	private final int replyCode;    回复状态码
             * 	                private final String replyText; 回复文本内容
             * 	                private final String exchange;  消息给哪个交换机
             * 	                private final String routingKey;消息使用的路由
             */
            @Override
            public void returnedMessage(ReturnedMessage returned) {

            }
        });
    }
}
